<template>
  <div>
    <el-card shadow="never" :body-style="{ padding: '10px' }">
      <!-- 卡片头部 -->
      <div slot="header">
        <el-button
          type="text"
          size="medium"
          plain
          icon="el-icon-back"
          @click="goBack"
          >返回上一页面</el-button
        >
        <el-divider direction="vertical"></el-divider>
        小节标题：<span class="head-font">{{ chapterTitle }}</span>
        <el-divider direction="vertical"></el-divider>
        题目总数：<span class="head-font">{{ totalNum }}</span>
      </div>
      <!-- 表格上方按钮 -->
      <div>
        <div style="float: left; margin-bottom: 10px">
          <!-- 从题库中批量添加题目 -->
          <el-button
            type="primary"
            plain
            icon="el-icon-circle-plus"
            size="mini"
            @click="searchQuestionBank"
            >选取题目</el-button
          >
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            @click="deleteList"
            >批量移除</el-button
          >
        </div>
        <div style="float: right">
          <el-tooltip class="item" effect="dark" content="刷新" placement="top">
            <el-button
              size="mini"
              circle
              icon="el-icon-refresh"
              @click="queryList"
            />
          </el-tooltip>
        </div>
      </div>
      <!-- 信息列表 -->
      <div style="float: left; width: 100%">
        <el-table
          border
          v-loading="listLoading"
          :header-cell-style="{ background: '#FAFAFA' }"
          :data="questionList"
          @selection-change="handleSelectionChange"
          height="750px"
          style="width: 100%"
        >
          <el-table-column type="selection" width="55"> </el-table-column>
          <el-table-column type="index" width="55"> </el-table-column>
          <el-table-column
            prop="id"
            label="id"
            width="150"
            :show-overflow-tooltip="true"
          >
          </el-table-column>
          <el-table-column prop="type" label="题型" width="100">
          </el-table-column>
          <el-table-column
            prop="question"
            label="题干"
            :show-overflow-tooltip="true"
          >
          </el-table-column>
          <el-table-column prop="correct" label="答案" width="180">
          </el-table-column>
          <el-table-column prop="gmtCreate" label="创建时间" width="180">
          </el-table-column>
          <el-table-column prop="gmtModified" label="更新时间" width="180">
          </el-table-column>
          <el-table-column
            fixed="right"
            label="操作"
            width="180"
            align="center"
          >
            <template slot-scope="scope">
              <el-button size="medium" type="text" @click="preview(scope.row)">
                详情
              </el-button>
              <el-button
                size="medium"
                type="text"
                @click="deleteOne(scope.row)"
              >
                移除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>
    <!-- 题目详情 -->
    <el-dialog title="题目详情" :visible.sync="previewDialog" width="30%">
      <el-row>{{ questionInfo.question }}</el-row>
      <div style="line-height: 1.8">
        <el-row :key="index" v-for="(item, index) in questionInfo.opt">
          <span>{{ String.fromCharCode(65 + index) }}</span>
          <span>{{ item }}</span>
        </el-row>
        <el-divider></el-divider>
        <el-row
          >答案：
          <span :key="item.id" v-for="item in questionInfo.correct">
            <span v-html="item"></span></span
        ></el-row>
        <el-divider></el-divider>
        <el-row
          >解析：<span v-if="questionInfo.analysis == ''">暂无解析</span
          ><span v-else>{{ questionInfo.analysis }}</span></el-row
        >
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="previewDialog = false">取 消</el-button>
        <el-button type="primary" @click="previewDialog = false"
          >确 定</el-button
        >
      </span>
    </el-dialog>
    <!-- 题库选择对话框 -->
    <el-dialog
      title="选取题目"
      :visible.sync="questionBankDialogVisible"
      width="70%"
    >
      <div>
        <!-- 搜索表单 -->
        <el-form :inline="true">
          <el-tag type="info">搜索题库</el-tag>
          <el-form-item label="题库标题" size="small">
            <el-input
              v-model="queryParams.title"
              placeholder="请输入题库标题"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item label="适用工种" size="small">
            <div class="block">
              <el-cascader
                v-model="queryParams.courseId"
                :options="typeOptions"
                placeholder="默认全部"
                :props="{
                  value: 'id',
                  label: 'courseName',
                  children: 'childrenList',
                  expandTrigger: 'hover',
                }"
                :show-all-levels="false"
                clearable
              ></el-cascader>
            </div>
          </el-form-item>
          <el-form-item size="small" label="适用职级">
            <el-select
              v-model="queryParams.gradeId"
              clearable
              placeholder="全部"
            >
              <el-option
                v-for="item in gradeList"
                :key="item.id"
                :label="item.grade"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item size="small">
            <el-button
              type="primary"
              icon="el-icon-search"
              @click="getQuestionList"
              >搜索</el-button
            >
            <el-button icon="el-icon-refresh" @click="resetQuery"
              >重置</el-button
            >
          </el-form-item>
        </el-form>
        <!-- 信息列表 -->
        <el-table
          border
          :header-cell-style="{ background: '#FAFAFA' }"
          :data="questionBankList"
          :default-sort="{ prop: 'gmtCreate', order: 'descending' }"
          height="50vh"
        >
          <el-table-column prop="eduTestInfo.title" label="标题">
          </el-table-column>
          <el-table-column prop="courseName" label="适用工种">
          </el-table-column>
          <el-table-column prop="grade" label="适用职级"> </el-table-column>
          <el-table-column
            label="创建时间"
            prop="gmtCreate"
            :show-overflow-tooltip="true"
          >
          </el-table-column>
          <el-table-column
            label="更新时间"
            prop="gmtModified"
            :show-overflow-tooltip="true"
          >
          </el-table-column>
          <el-table-column label="操作" width="180" align="center">
            <template slot-scope="scope">
              <el-button
                type="text"
                @click="openQuestionBank(scope.row.eduTestId)"
                >选取题目</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>
    <!-- 查看题目对话框 -->
    <el-dialog
      title="添加小节题目"
      :visible.sync="questionBankDialogVisible2"
      width="70%"
    >
      <el-tag type="info">勾选题目</el-tag>
      <el-table
        border
        :header-cell-style="{ background: '#FAFAFA' }"
        :data="questionList2"
        @selection-change="handleSelectionChange2"
        height="60vh"
        style="width: 100%"
      >
        <el-table-column type="selection" width="55"> </el-table-column>
        <el-table-column type="index" width="55"> </el-table-column>
        <el-table-column
          prop="id"
          label="id"
          width="150"
          :show-overflow-tooltip="true"
        >
        </el-table-column>
        <el-table-column prop="type" label="题型" width="100">
        </el-table-column>
        <el-table-column
          prop="question"
          label="题干"
          :show-overflow-tooltip="true"
        >
        </el-table-column>
        <el-table-column prop="correct" label="答案" width="100">
        </el-table-column>
        <el-table-column prop="gmtCreate" label="创建时间" width="180">
        </el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button @click="questionBankDialogVisible2 = false">取 消</el-button>
        <el-button type="primary" @click="submitAddQuestion">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { queryTestPaperList } from "@/api/testPaper";
import { getCategory } from "@/api/classification";
import { getGradeList } from "@/api/grade";
import {
  queryQuestion,
  queryQuestionByChapter,
  addQuestionByChapter,
  removeQuestionByChapter,
} from "@/api/question";
export default {
  //小节题目
  name: "chapterQuestion",
  data: function () {
    return {
      //表格加载遮罩
      listLoading: "false",
      //小节编号
      chapterId: this.$route.query.chapterId,
      //小节标题
      chapterTitle: this.$route.query.chapterTitle,
      //题目总数
      totalNum: "",
      //小节的题目列表
      questionList: [],
      //预览对话框
      previewDialog: false,
      //题目预览信息
      questionInfo: "",
      //批量移除列表
      selectRemoveList: "",
      //题库列表
      questionBankList: [],
      //题库选择对话框
      questionBankDialogVisible: false,
      //题库选择对话框查询参数
      queryParams: {
        title: "",
        courseId: "",
        gradeId: "",
        type: "1",
      },
      //工种列表
      typeOptions: [],
      //职级列表
      gradeList: [],
      //查看题库的题目对话框
      questionBankDialogVisible2: false,
      //查看题库的题目列表
      questionList2: [],
      //选择添加的题目id列表
      selectAddList: [],
    };
  },
  created: function () {
    this.queryList();
  },
  methods: {
    //根据小节编号查找的题目列表
    queryList() {
      //获取职级列表
      getGradeList().then((res) => {
        const data = res.data;
        this.gradeList = data.resList;
      });
      //分类列表
      getCategory(0, this.companyId).then((res) => {
        const data = res.data;
        this.typeOptions = this.deleteChildren(data.resList);
      });
      let that = this;
      this.listLoading = true;
      queryQuestionByChapter(this.chapterId).then((res) => {
        that.totalNum = res.data.total;
        that.questionList = res.data.resList;
        this.listLoading = false;
      });
    },
    //删除childrenList
    deleteChildren(arr) {
      let childs = arr;
      for (let i = childs.length; i--; i > 0) {
        if (childs[i].childrenList) {
          if (childs[i].childrenList.length) {
            this.deleteChildren(childs[i].childrenList);
          } else {
            delete childs[i].childrenList;
          }
        }
      }
      return arr;
    },
    //打开题库选择对话框
    searchQuestionBank() {
      this.questionBankDialogVisible = true;
      this.getQuestionList();
    },
    //查看题库的题目
    openQuestionBank(questionBankId) {
      this.questionBankDialogVisible2 = true;
      queryQuestion(questionBankId).then((res) => {
        this.questionList2 = res.data.resList;
      });
    },
    //添加题目
    submitAddQuestion() {
      var self = this;
      if (this.selectAddList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("此操作将添加选中的所有题目, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          var idArray = [];
          self.selectAddList.forEach(function (question) {
            idArray.push(question.id);
          });
          self.addAjax(idArray);
        })
        .catch(() => {});
    },
    //添加题目的Ajax请求
    addAjax: function (idArray) {
      var that = this;
      addQuestionByChapter(this.chapterId, idArray).then((res) => {
        if (res.success == true) {
          this.$message({
            message: "添加成功",
            type: "success",
          });
          that.queryList();
          that.questionBankDialogVisible2 = false;
        } else {
          this.$message({
            message: "添加失败",
            type: "error",
          });
        }
      });
    },
    //搜索题库
    getQuestionList() {
      if (this.queryParams.courseId.length > 0) {
        this.queryParams.courseId =
          this.queryParams.courseId[this.queryParams.courseId.length - 1];
      }
      queryTestPaperList(this.queryParams, 1, 10000, this.companyId).then(
        (response) => {
          this.questionBankList = response.data.resList;
        }
      );
    },
    //预览
    preview(question) {
      this.questionInfo = question;
      this.previewDialog = true;
    },
    //移除单个题目
    deleteOne(question) {
      var self = this;
      this.$confirm("此操作将移除该题目, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          var idArray = []; //移除列表
          idArray.push(question.id);
          self.deleteAjax(idArray);
        })
        .catch(() => {});
    },
    //选择移除的id列表
    handleSelectionChange: function (val) {
      this.selectRemoveList = val;
    },
    //选择添加的题目id列表
    handleSelectionChange2: function (val) {
      this.selectAddList = val;
    },
    //批量移除题目
    deleteList() {
      var self = this;
      if (this.selectRemoveList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("此操作将移除选中的所有题目, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          var idArray = [];
          self.selectRemoveList.forEach(function (question) {
            idArray.push(question.id);
          });
          self.deleteAjax(idArray);
        })
        .catch(() => {});
    },
    //移除的Ajax请求
    deleteAjax: function (idArray) {
      var that = this;
      removeQuestionByChapter(idArray).then((res) => {
        if (res.success == true) {
          this.$message({
            message: "移除成功",
            type: "success",
          });
          that.queryList();
        } else {
          this.$message({
            message: "移除失败",
            type: "error",
          });
        }
      });
    },
    //重置查询参数
    resetQuery() {
      this.queryParams = {
        title: "",
        courseId: "",
        gradeId: "",
        type: "1",
      };
      this.getQuestionList();
    },
    //返回
    goBack() {
      this.$router.go(-1);
    },
    //关闭对话框的提示框
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then((_) => {
          done();
        })
        .catch((_) => {});
    },
  },
};
</script>
<style scoped>
.head-font {
  font-weight: bold;
}
.options {
  margin-bottom: 10px;
}
</style>